package com.haiyou.common.id;

import org.springframework.stereotype.Component;


import com.xfvape.uid.impl.DefaultUidGenerator;
import com.xfvape.uid.worker.WorkerIdAssigner;
import com.haiyou.common.constants.ErrCode;
import com.haiyou.common.spring.component.LifecycleableComponent;
import com.haiyou.common.system.Properties;
import com.haiyou.common.util.check.Assert;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * 
 * @Description: 百度雪花id生成器 生成器  注意:需要唯一的 server.node.id
 * @author xingyuan
 * @date 2022年10月21日 下午6:06:58
 */
@Slf4j
@Component
public class UidGenerator implements LifecycleableComponent{

	/**
	 * id 生成器
	 */
	private com.xfvape.uid.UidGenerator generator;
	
	
	/**
	 * 获取下一个uid
	 * @return
	 */
	public long nextUid(){
		Assert.isTrue(generator != null, ErrCode.ERROR_PARAMETER,"UidGenerator not init");
		return generator.getUID();
	}
	
	@Override
	public void init() {
		
		long nodeId = Properties.server_node_id();
		
		if(nodeId <= 0) {
			log.error("server node not set,nodeId:{} ,UidGenerator not init");
			return ;
		}
		
		DefaultUidGenerator defaultUidGenerator = new DefaultUidGenerator();
		
		//设置NodeId
		defaultUidGenerator.setWorkerIdAssigner(new WorkerIdAssigner() {
			@Override
			public long assignWorkerId() {
				return nodeId;
			}
		});
		
		try {
			defaultUidGenerator.afterPropertiesSet();
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			return ;
		}
		this.generator = defaultUidGenerator;
	}

	
	@Override
	public void destory() {
		
	}

}
